package com.example.ffepeg.ffeImg;

import java.io.IOException;

/**
 * @author TS
 * @date 2024/11/5 18:09
 */
public class FFtestShui {
    public static void main(String[] args) throws IOException {  //上面的印记  x = 125  y = 150    下面的印记 x = 125  y = 530

       // String delteImagePath = "https://pushimg.liecaizhijia.com/video/image/2024-10-20/6cf96063-d2d0-4c2c-a936-8e90c35d2286.png";
        String delteImagePath = "src/main/resources/file/logo/outImageMp4.png";
        String outputImagePath = "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\output.png";
        int x = 1250; //水印logo的x坐标
        int y = 900; //水印logo的y坐标
        String logoImagePath = "https://pushimg.liecaizhijia.com/image_example/img/c6dd68e8-31da-4af8-b255-14082a279fff51826714613360d6ca65957966e675a.png";
        replaceWatermark(delteImagePath, outputImagePath, logoImagePath, x, y);
    }
    public static boolean replaceWatermark(String inputImagePath, String outputImagePath, String watermarkImagePath, int x, int y) throws IOException {
        // 参数校验
        if (inputImagePath == null || outputImagePath == null || watermarkImagePath == null) {
            throw new IllegalArgumentException("路径不能为空");
        }

        // 构建FFmpeg命令
        ProcessBuilder processBuilder = new ProcessBuilder(
                "ffmpeg", "-i", inputImagePath, "-i", watermarkImagePath,
                "-filter_complex", String.format("overlay=%d:%d", x, y),
                outputImagePath
        );

        // 设置重定向错误流
        processBuilder.redirectErrorStream(true);

        // 启动进程
        Process process = processBuilder.start();

        // 等待进程完成
        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                // 如果FFmpeg返回非零退出码，表示执行失败
                throw new IOException("FFmpeg执行失败，退出码: " + exitCode);
            }
        } catch (InterruptedException | IOException e) {
            Thread.currentThread().interrupt();
            throw new IOException("水印替换过程中断", e);
        } finally {
            // 关闭进程
            process.destroy();
        }
        return true;
    }
}
